param(
    [Parameter(Mandatory=$true)]
    [int]$Port
)

Write-Host "Killing processes on port $Port..." -ForegroundColor Yellow

# 查找占用指定端口的进程
$processes = Get-NetTCPConnection -LocalPort $Port -ErrorAction SilentlyContinue | 
    Where-Object { $_.State -eq "Listen" -or $_.State -eq "Established" }

if ($processes.Count -eq 0) {
    Write-Host "No processes found on port $Port" -ForegroundColor Green
    exit
}

Write-Host "Found $($processes.Count) process(es) on port $Port" -ForegroundColor Red

$killedCount = 0
foreach ($process in $processes) {
    $pid = $process.OwningProcess
    try {
        $processInfo = Get-Process -Id $pid -ErrorAction SilentlyContinue
        if ($processInfo) {
            Write-Host "Killing process $pid ($($processInfo.ProcessName))" -ForegroundColor Cyan
            Stop-Process -Id $pid -Force -ErrorAction Stop
            Write-Host "Process $pid killed successfully" -ForegroundColor Green
            $killedCount++
        } else {
            Write-Host "Process $pid not found or already terminated" -ForegroundColor Yellow
        }
    }
    catch {
        Write-Host "Failed to kill process $pid : $($_.Exception.Message)" -ForegroundColor Red
    }
}

Write-Host "Killed $killedCount process(es)" -ForegroundColor Cyan

# 验证端口是否已释放
Start-Sleep -Seconds 2
$remaining = Get-NetTCPConnection -LocalPort $Port -ErrorAction SilentlyContinue | 
    Where-Object { $_.State -eq "Listen" -or $_.State -eq "Established" }

if ($remaining) {
    Write-Host "Warning: Port $Port still in use by $($remaining.Count) connection(s)" -ForegroundColor Yellow
    $remaining | ForEach-Object {
        Write-Host "  PID: $($_.OwningProcess), State: $($_.State)" -ForegroundColor Gray
    }
} else {
    Write-Host "Port $Port released successfully" -ForegroundColor Green
}